'use client'

import styles from "./page.module.css";
import {Button, Form, message} from "antd";
import {Questionnaire} from '@/types/Index'
import Api from "@/api/api";
import {useEffect, useState} from "react";
import CheckboxTpl from "@/components/CheckboxTpl";
import InputTpl from "@/components/InputTpl";
import RadioTpl from "@/components/RadioTpl";

function Home() {

  const [form] = Form.useForm()

  const onClick = async () => {
    try {
      const values = await form.validateFields()
      console.log('Success:', values)
      submitQuestion(values).then(res => {
        if (res.code === 200) {
          message.success('提交成功!')
        } else {
          message.error(res.msg)
        }
      })
    } catch (errorInfo) {
      console.log('Failed:', errorInfo)
    }

  }

  const [list, setList] = useState<Questionnaire[]>([])

  useEffect(() => {
    getList()

    console.log(12)
  }, [])

  function getList() {
    const api = new Api()
    api.getQuestionList("7225923123225309184").then(res => {
      if (res.code === 0) {
        console.log(res)
        setList(res.data)
      }
    })
  }

  function createQuestionDom() {
    return list.map((item, index) => {
      let no = index + 1
      let rules = []
      if (item.required) {
        rules.push({ required: true, message: '请填写或者选择题目!' })
      }
      return (
        <Form.Item key={index} label={item.questionName} name={item.questionId} rules={rules}>
          {createDetailDom(item)}
        </Form.Item>
      )
    })
  }

  function onChange(v: any) {
    console.log(v)
  }

  function createDetailDom(item: Questionnaire) {
    switch (item.questionType) {
      case 2:
        return <CheckboxTpl items={item.questionBankItemVoList} onChange={onChange}/>
      case 1:
        return <InputTpl onChange={onChange}/>
      case 0:
        return <RadioTpl items={item.questionBankItemVoList} onChange={onChange}/>
      default:
        return <></>
    }
  }

  return (
    <main className={styles.main}>
      <Form
        form={form}
        initialValues={{ layout: 'vertical' }}
        style={{ maxWidth: 600 }}
      >
        {createQuestionDom()}
        <Form.Item>
          <Button type="primary" onClick={onClick}>
            提交
          </Button>
        </Form.Item>
      </Form>
    </main>
  )

}

export default Home
